package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.MyfavoriteMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.Myfavorite;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.MyfavoriteService;
import com.qingcheng.util.CacheKey;
import com.qingcheng.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MyfavoriteServiceImpl implements MyfavoriteService {
    @Autowired
    private CartService cartService;

    @Autowired
    private MyfavoriteMapper myfavoriteMapper;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Myfavorite> findAll() {
        return myfavoriteMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Myfavorite> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Myfavorite> myfavorites = (Page<Myfavorite>) myfavoriteMapper.selectAll();
        return new PageResult<Myfavorite>(myfavorites.getTotal(), myfavorites.getResult());
    }

    /**
     * 条件查询
     *
     * @param
     * @return
     */
    public List<Map<String, Object>> findList(String username) {

        Example example = new Example(Myfavorite.class);
        Example.Criteria criteria = example.createCriteria();
        //使用用户名查询关注商品集合
        criteria.andEqualTo("username", username);
        List<Myfavorite> myfavoriteList = myfavoriteMapper.selectByExample(example);
        //查询结果为null则新建一个集合
        if (myfavoriteList == null) {
            return new ArrayList();
        }

        //List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        //封装参数
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for (Myfavorite myfavorite : myfavoriteList) {
            Map map = new HashMap();
            map.put("item", myfavorite);
            map.put("checked", false);
            list.add(map);
            //存入缓存
            redisTemplate.boundHashOps(CacheKey.My_Collection).put(username, list);
        }
        return list;
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Myfavorite> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Myfavorite> myfavorites = (Page<Myfavorite>) myfavoriteMapper.selectByExample(example);
        return new PageResult<Myfavorite>(myfavorites.getTotal(), myfavorites.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Myfavorite findById(Integer id) {
        return myfavoriteMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     *
     * @param
     */
    @Reference
    private SkuService skuService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 从购物车添加商品到我的关注
     * @param skuId
     * @param username
     * @param num
     */
    public void add(String skuId, String username, Integer num) {
        //数量不为零调用carService删除购物车商品
        if (num != 0) {
            cartService.saveGoodsToCart(username, skuId, num);
        }
        //根据用户名查询关注集合
        List<Map<String, Object>> listMap = findList(username);
        if (listMap != null) {
            for (Map<String, Object> stringObjectMap : listMap) {
                Myfavorite item = (Myfavorite) stringObjectMap.get("item");
                //关注商品已存在直接返回
                if (item.getSkuId().equals(skuId)) {
                    return;
                }
            }
        }

        Myfavorite myfavorite = new Myfavorite();
        //数据库中查找sku
        Sku sku = skuService.findById(skuId);
        if (sku == null) {
            throw new RuntimeException("没有这个商品");
        }
        //从sku中查询数据存入
        myfavorite.setId(idWorker.nextId() + "");
        myfavorite.setSkuId(skuId);
        myfavorite.setName(sku.getName());
        myfavorite.setSpuId(sku.getSpuId());
        myfavorite.setCategoryId(sku.getCategoryId());
        myfavorite.setImage(sku.getImage());
        myfavorite.setPrice(sku.getPrice());
        myfavorite.setUsername(username);
        myfavorite.setWeight(sku.getWeight());
        myfavorite.setBrandName(sku.getBrandName());
        myfavorite.setCommentNum(sku.getCommentNum());
        myfavorite.setStatus(sku.getStatus());
        //存入数据库
        myfavoriteMapper.insert(myfavorite);
        //存入缓存
        Map map = new HashMap();
        map.put("item", myfavorite);
        map.put("checked", false);
        redisTemplate.boundHashOps(CacheKey.My_Collection).put(username, map);

    }


    /**
     * 修改
     * @param myfavorite
     */
    public void update(Myfavorite myfavorite) {
        myfavoriteMapper.updateByPrimaryKeySelective(myfavorite);
    }

    /**
     * 删除
     * @param id
     */
    public void delete(Integer id) {
        myfavoriteMapper.deleteByPrimaryKey(id);
    }


    /**
     * 添加选中的到关注
     * @param
     */

    public void adds(String username) {
        //获取选中的购物车
        List<Map<String, Object>> cartList = cartService.findCartList(username).stream().filter(cart -> (boolean) cart.get("checked") == true).collect(Collectors.toList());
        for (Map<String, Object> stringObjectMap : cartList) {
            OrderItem orderItem = (OrderItem) stringObjectMap.get("item");
            add(orderItem.getSkuId(), username, 0);
        }
        //获取未选中的购物车，删除选中的
        List<Map<String, Object>> cartList2 = cartService.findCartList(username).stream().filter(cart -> (boolean) cart.get("checked") == false).collect(Collectors.toList());
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartList2);//存入缓存
    }


    /**
     * 从redis中获取我的关注数据
     * @param username
     * @return
     */
    @Override
    public List<Map<String, Object>> findMyCollection(String username) {
        System.out.println("从redis中获取我的收藏数据:" + username);
        List<Map<String, Object>> cartList = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.My_Collection).get(username);
        System.out.println("从redis中获取我的收藏数据:" + cartList);
        System.out.println("-----------------------------------");
        if (cartList == null) {
            return new ArrayList<Map<String, Object>>();
        }
        return cartList;
    }

    /**
     * 删除单个关注
     * @param username
     * @param skuId
     */
    @Override
    public void deleteMyCollectionOne(String username, String skuId) {
        //从缓存中查询所有选中的关注数据
       /* List<Map<String, Object>> myCollection = findMyCollection(username)
                .stream()
                .filter(cart -> (boolean) cart.get("checked") == false)
                .collect(Collectors.toList());*/
        List<Map<String, Object>> mapList = findMyCollection(username);
        for (Map<String, Object> map : mapList) {
            Myfavorite myfavorite = (Myfavorite) map.get("item");
            if (skuId.equals(myfavorite.getSkuId())) {
                mapList.remove(map);
                //删除对应的数据库
                myfavoriteMapper.delete(myfavorite);
                break;
            }
        }
        //跟新redis缓存
        redisTemplate.boundHashOps(CacheKey.My_Collection).put(username, mapList);

    }


    /**
     * 删除所有选中关注
     * @param username
     */
    @Override
    public void deleteMyCollection(String username) {
        List<Map<String, Object>> myCollection = findMyCollection(username)
                .stream()
                .filter(cart -> (boolean) cart.get("checked") == false)
                .collect(Collectors.toList());

        List<Map<String, Object>> myCollection1 = findMyCollection(username)
                .stream()
                .filter(cart -> (boolean) cart.get("checked") == true)
                .collect(Collectors.toList());

        redisTemplate.boundHashOps(CacheKey.My_Collection).put(username, myCollection);//存入缓存

        for (Map<String, Object> map : myCollection1) {
            Myfavorite myfavorite = (Myfavorite) map.get("item");
            Example example = new Example(Myfavorite.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("skuId",myfavorite.getSkuId());
            myfavoriteMapper.deleteByExample(example);
        }
    }


    //获取最新的我的关注列表
   /* @Override
    public List<Map<String, Object>> findMyCollectionList(String skuId) {
        //获取选中的我的收藏
        List<Map<String, Object>> cartList = cartService.findCartList(skuId);
        //循环我的收藏列表，重新读取每个商品的最新价格
        for (Map<String, Object> stringObjectMap : cartList) {
            OrderItem orderItem = (OrderItem) stringObjectMap.get("item");
            Sku sku = skuService.findById(orderItem.getSkuId());
            orderItem.setPrice(sku.getPrice());//更新价格
            orderItem.setMoney(sku.getPrice() * orderItem.getNum());//存入缓存
        }
        //保存最新我的收藏
        redisTemplate.boundHashOps(CacheKey.My_Collection).put("skuId", cartList);
        return cartList;
    }*/


    /**
     * 修改单个商品状态
     * @param username
     * @param skuId
     * @return
     */
    @Override
    public boolean updateMyCollection(String username, String skuId) {
        //获取购物车
        List<Map<String, Object>> mapList = findMyCollection(username);

        //判断缓存中是否含有已购物商品
        boolean isOk = false;
        for (Map<String, Object> map : mapList) {


//            OrderItem orderItem = (OrderItem) map.get("item");
            Myfavorite myfavorite = (Myfavorite) map.get("item");
            if (myfavorite.getSkuId().equals(skuId)) {
                boolean checked = (boolean) map.get("checked");
                if (checked==false){
                    map.put("checked", true);
                    isOk = true;//执行成功
                    break;
                }else {
                    map.put("checked", false);
                    isOk = true;//执行成功
                    break;
                }
            }
        }
        if (isOk) {
            redisTemplate.boundHashOps(CacheKey.My_Collection).put(username, mapList);//存入缓存
        }
        return isOk;
    }

    /**
     * 全选    （功能暂未实现）
     * @param username
     * @param checked
     */
    @Override
    public void selectAll(String username, boolean checked) {
        //修改redis商品缓存
        List<Map<String, Object>> mapList = findMyCollection(username);
        for (Map<String, Object> map : mapList) {
            map.put("checked",checked);
        }
        //将全选添加到缓存
        redisTemplate.boundHashOps(CacheKey.My_Collection).put(username,mapList);
    }

    /**功能描述
     * 保存商品到购物车
     * @date 2019/9/21 0021
     * @param
     * @return void
     */
    @Override
    public void saveGoodsToCart(String username, String skuId, Integer num) {
        //保存商品到购物车
        cartService.saveGoodsToCart(username,skuId,num);

//        //将商品从我的收藏删除
//        Example example = new Example(Myfavorite.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("skuId",skuId);
//        myfavoriteMapper.deleteByExample(example);
    }

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Myfavorite.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // skuId
            if (searchMap.get("skuId") != null && !"".equals(searchMap.get("skuId"))) {
                criteria.andLike("skuId", "%" + searchMap.get("skuId") + "%");
            }
            // spuId
            if (searchMap.get("spuId") != null && !"".equals(searchMap.get("spuId"))) {
                criteria.andLike("spuId", "%" + searchMap.get("spuId") + "%");
            }
            // SKU名称
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 商品图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 品牌名称
            if (searchMap.get("brandName") != null && !"".equals(searchMap.get("brandName"))) {
                criteria.andLike("brandName", "%" + searchMap.get("brandName") + "%");
            }
            // 商品状态 1-正常，2-下架，3-删除
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andLike("status", "%" + searchMap.get("status") + "%");
            }

            // ID
            if (searchMap.get("id") != null) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 第三级分类ID
            if (searchMap.get("categoryId") != null) {
                criteria.andEqualTo("categoryId", searchMap.get("categoryId"));
            }
            // 单件重量（克）
            if (searchMap.get("weight") != null) {
                criteria.andEqualTo("weight", searchMap.get("weight"));
            }
            // 商品单价（分）
            if (searchMap.get("price") != null) {
                criteria.andEqualTo("price", searchMap.get("price"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
